package com.bird.thread.base.sixstaus.sitchstatus;

/**
 * @author: bird
 * @Data: 2021/6/30 10:47
 * @description: 线程状态的之间的流转之：
 * new--->runnable--->blocked--->runnable--->terminated
 * <p>
 * 所谓的锁 就是cpu的资源。
 */
public class newRunnableBlockedTerminated implements Runnable {


    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("线程状态的流转: ");
        newRunnableBlockedTerminated runnable = new newRunnableBlockedTerminated();
        Thread thread1 = new Thread(runnable);
        thread1.start();

        Thread thread2 = new Thread(runnable);
        // NEW 状态
        System.out.println(thread2.getState());
        //    sb.append(thread2.getState()).append("-->");
        thread2.start();
        //打印runnable-状态
        System.out.println(thread2.getState());
        //sb.append(thread2.getState()).append("-->");

        try {
            Thread.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 打印 blocked-状态
        System.out.println(thread2.getState());
        //sb.append(thread2.getState()).append("-->");

        while ("RUNNABLE".equals(thread2.getState())) {
            System.out.println(thread2.getState());
        }


        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印 RUNNABLE-状态
        System.out.println(thread2.getState());
        //   sb.append(thread2.getState());
        //   System.out.println(sb.toString());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //打印 TERMINATED 结束
        System.out.println(thread2.getState());
    }


    @Override
    public void run() {
        sync();
    }


    // 当一个线程进入 被synchronized关键字修饰的代码块/方法块的时候,
    // 并且该锁已经被其它线程拿走了,那么该线程的状态就是 Blocked.
    private synchronized void sync() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
